import logging
import time
import os

from flask import make_response, request
from flask_login import current_user
from flask_restful import abort
from redash import models, settings
from redash.handlers.base import BaseResource, get_object_or_404, record_event


class ImageUploadResource(BaseResource):
    def post(self):
        file = request.files['file']

        basepath = os.path.abspath(settings.DAZ_FILES) 
        if not os.path.exists(basepath):
            try:
                os.mkdir(basepath)
            except Exception as e:
                logging.exception(e)
                return None                

        basepath = os.path.abspath(os.path.join(settings.DAZ_FILES, self.current_org.slug)) 
        if not os.path.exists(basepath):
            try:
                os.mkdir(basepath)
            except Exception as e:
                logging.exception(e)
                return None                

        filename = str(self.current_user.id) + "_" + file.filename
        fullname = os.path.join(basepath, filename)
        if os.path.isfile(fullname):
            os.remove(fullname)

        file.save(fullname)
        return self.current_org.slug + "/" + filename
